package com.tiger.userClient.http.auth;


import com.tiger.common.IpToAddress;
import com.tiger.common.Jwt;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class AuthService {
    private final IpToAddress ipToAddress;


    private final Jwt jwt;

    public AuthService(IpToAddress ipToAddress, Jwt jwt) {
        this.ipToAddress = ipToAddress;
        this.jwt = jwt;
    }


    public String getDomain(HttpServletRequest request) {
        String scheme = request.getScheme();

        // 获取服务器名（域名）
        String serverName = request.getServerName();

        // 获取端口号，如果需要的话
        int port = request.getServerPort();

        // 组合成完整的域名，包括协议头
        String domain = scheme + "://" + serverName;
        if (port != 80 && port != 443) { // 非标准端口需要添加端口号
            domain += ":" + port;
        }

        return domain;
    }

    public long getJwtExpire() {
        return jwt.getJwtExpire();
    }


    public String makeToken(long id, String role, String key, long time) {
        Map<String, Object> payload = new HashMap<>();

        Random rand = new Random();
        int randomNum = rand.nextInt(5) + 3; // 这将生成一个3到10之间的随机数（包括3和10）
        payload.put("k", id);
        payload.put("key", key);
        payload.put("v", id * randomNum);
        payload.put("time", time);
        payload.put("role", role);

        return jwt.createToken(payload);
    }

    @Async
    public void ipToLogin(String ip) {
        ipToAddress.convert(ip, true);
    }

    public String getLocation(String ip) {
        return ipToAddress.getAddress(ip);
    }
}
